<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入名称" clearable
                          @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="预约" prop="appoint">
                <el-select v-model="queryParams.appoint" placeholder="请选择预约" clearable>
                    <el-option v-for="dict in dict.type.ex_exam_appoint_dict" :key="dict.value" :label="dict.label"
                               :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="固定组卷" prop="fixed">
                <el-select v-model="queryParams.fixed" placeholder="请选择固定组卷" clearable>
                    <el-option v-for="dict in dict.type.ex_exam_fixed_dict" :key="dict.value" :label="dict.label"
                               :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
                <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择开始时间"></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
                <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择结束时间"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['ex:exam:add']">创建考试
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                           @click="handleDelete" v-hasPermi="['ex:exam:remove']">删除
                </el-button>
            </el-col>
            <!--            <el-col :span="1.5">-->
            <!--                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['ex:exam:export']">导出</el-button>-->
            <!--            </el-col>-->
            <el-col :span="1.5">
                <el-button type="info" plain icon="el-icon-phone-outline" size="mini" @click="handleMyAppoint">
                    我的考试
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="examList" @selection-change="handleSelectionChange" :height="table_height">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="名称" align="center" prop="name"/>
            <el-table-column label="考试时长" align="center" prop="duration" :formatter="second_format"/>
            <el-table-column label="总题数" align="center" prop="questionCount"/>
            <el-table-column label="是否允许预约" align="center" prop="appoint">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.ex_exam_appoint_dict" :value="scope.row.appoint"/>
                </template>
            </el-table-column>
            <el-table-column label="固定组卷" align="center" prop="fixed">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.ex_exam_fixed_dict" :value="scope.row.fixed"/>
                </template>
            </el-table-column>
            <el-table-column label="开始时间" align="center" prop="startTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="预约" align="center" class-name="small-padding fixed-width" width="200">
                <template slot-scope="scope">
                    <el-tag v-if="contain(exam_record_ids,scope.row.id)" type="danger">已预约</el-tag>
                    <el-popover v-else-if="isCanAppoint(scope.row)" placement="left-start" width="270" v-model="scope.row.visible" v-hasPermi="['ex:exam:appoint']">
                        <el-form ref="appoint_form" :model="appoint_form" :rules="rules" label-width="10px">
                            <el-form-item prop="appointDate">
                                <el-select v-model="appoint_form.appointDate" placeholder="请选择考试时间" clearable>
                                    <el-option v-for="item in getRange(scope.row)" :key="item" :label="item" :value="item"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <div style="float: right;padding-right: 30px;">
                                    <el-button size="mini" type="text" @click="appointCancel(scope.row)">取消
                                    </el-button>
                                    <el-button type="primary" size="mini" @click="appoint(scope.row)">预约</el-button>
                                </div>
                            </el-form-item>
                        </el-form>
                        <el-button slot="reference" size="mini" type="success" plain icon="el-icon-phone-outline" style="width: 58px" v-hasPermi="['ex:exam:appoint']"> 预约</el-button>
                    </el-popover>
                    <span v-else> — </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-hasPermi="['ex:exam:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['ex:exam:remove']">删除</el-button>
                    <el-button size="mini" type="text" v-if="beforeNow(scope.row.endTime)" icon="el-icon-user" @click="handleAllot(scope.row)" v-hasPermi="['ex:exam:edit']">分配用户
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>

        <!-- 添加考试管理对话框 -->
        <el-dialog title="创建考试" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="add_form" :model="form" :rules="rules" label-width="80px" label-position="left" size="mini">
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入名称" style="width: 200px" clearable>
                                <el-tooltip slot="append" class="item" effect="dark" content="自动生成" placement="top">
                                    <el-button icon="el-icon-help" @click="generateName"></el-button>
                                </el-tooltip>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="时长(时)" prop="timer">
                            <el-time-select v-model="form.timer" value-format="HH:mm:ss" :picker-options="{start: '00:15', step: '00:15',end: '06:00'}" placeholder="选择时长"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                        <el-form-item label="允许预约" prop="appoint">
                            <el-radio-group v-model="form.appoint">
                                <el-radio v-for="dict in dict.type.ex_exam_appoint_dict" :key="dict.value"
                                          :label="parseInt(dict.value)">{{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="固定组卷" prop="fixed">
                            <el-radio-group v-model="form.fixed">
                                <el-radio v-for="dict in dict.type.ex_exam_fixed_dict" :key="dict.value"
                                          :label="parseInt(dict.value)">{{ dict.label }}
                                </el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="考试时间" prop="timeRange">
                    <el-date-picker v-model="form.timeRange" type="daterange" :picker-options="pickerOptions"
                                    range-separator=" ~ " value-format="yyyy-MM-dd" start-placeholder="开始日期"
                                    end-placeholder="结束日期" align="right"></el-date-picker>
                </el-form-item>
                <el-form-item label="选题策略" prop="sig">
                    <el-radio-group v-model="form.sig">
                        <el-radio label="ratio">按题库比例</el-radio>
                        <el-radio label="average">平均选择</el-radio>
                        <el-radio label="optional">自选</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="题目数量" prop="total" v-if="form.sig !== 'optional'">
                    <el-input-number size="small" :max="questionTotal" :min="0" v-model="form.questionCount"
                                     @input="$forceUpdate()" controls-position="right"/>
                </el-form-item>
                <el-form-item label="选题策略" prop="checkeds">
                    <div class="customer-table">
                        <el-table v-loading="loading" ref="questionTable" :data="questionList" height="355" width="100%"
                                  @selection-change="handleQuestionChange" :show-header="false" size="small">
                            <el-table-column type="selection" width="45"/>
                            <el-table-column width="400">
                                <template slot-scope="scope">
                                    <el-row :gutter="10" class="mb8">
                                        <el-col :span="1.7">
                                            <dict-tag :options="dict.type.ex_question_topic_dict"
                                                      :value="scope.row.topic"/>
                                        </el-col>
                                        <el-col :span="1">({{ scope.row.count }})</el-col>
                                    </el-row>
                                </template>
                            </el-table-column>
                            <el-table-column>
                                <template slot-scope="scope" v-if="form.sig === 'optional' && scope.isSelected">
                                    <el-input-number size="small" :min="0" :max="scope.row.count" @change="$forceUpdate"
                                                     v-model="scope.row.number"
                                                     controls-position="right"></el-input-number>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitAddForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 修改考试管理对话框 -->
        <el-dialog title="修改考试" :visible.sync="edit_open" width="500px" append-to-body>
            <el-form ref="edit_form" :model="form" :rules="rules" label-width="80px" label-position="left" size="mini">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入名称" style="width: 200px" clearable>
                        <el-tooltip slot="append" class="item" effect="dark" content="自动生成" placement="top">
                            <el-button icon="el-icon-help" @click="generateName"></el-button>
                        </el-tooltip>
                    </el-input>
                </el-form-item>
                <el-form-item label="时长(时)" prop="timer">
                    <el-time-select v-model="form.timer" value-format="HH:mm:ss" :picker-options="{start: '00:15', step: '00:15',end: '06:00'}" placeholder="选择时长"/>
                </el-form-item>

                <el-form-item label="允许预约" prop="appoint">
                    <el-radio-group v-model="form.appoint">
                        <el-radio v-for="dict in dict.type.ex_exam_appoint_dict" :key="dict.value"
                                  :label="parseInt(dict.value)">{{ dict.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="考试时间" prop="timeRange">
                    <el-date-picker v-model="form.timeRange" type="daterange" :picker-options="pickerOptions"
                                    range-separator=" ~ " value-format="yyyy-MM-dd" start-placeholder="开始日期"
                                    end-placeholder="结束日期" align="right"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitEditForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 我的预约抽屉 -->
        <el-drawer :with-header="false" :visible.sync="appoint_open" direction="rtl" size="70%" :destroy-on-close="true"
                   append-to-body>
            <record_my @resetList="getList"/>
        </el-drawer>

        <!-- 分配用户抽屉 -->
        <el-drawer :title="allot_ex.name" :visible.sync="allot_open" direction="rtl" size="70%" :destroy-on-close="true"
                   append-to-body>
            <allot :exam="allot_ex"/>
        </el-drawer>

    </div>
</template>

<script>
import {listExam, delExam, createExam, updateExam} from "@/api/ex/exam";
import {parseTime} from "@/utils/ruoyi";
import {arrSumByKey, fillNode, contain} from "@/utils/zzDouUtils/arrayUtil";
import {timeToSecond, secondFormat, beforeNow, getRangeDay, date, afterNow, now} from "@/utils/zzDouUtils/dateUtil";
import {get_question_ids_group_by_topic} from "@/api/ex/question";
import {get_appoint_exam_ids, appoint} from "@/api/ex/ex_record";
import record_my from "@/views/ex/record/index_my.vue";
import allot from "@/views/ex/exam/allot.vue";
import {copyObj} from "@/utils/zzDouUtils/objUtil";

export default {
    name: "Exam",
    components: {record_my, allot},
    dicts: ['ex_exam_fixed_dict', 'ex_exam_appoint_dict', 'ex_question_topic_dict'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 考试管理表格数据
            examList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            edit_open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                duration: null,
                appoint: null,
                fixed: null,
                startTime: null,
                endTime: null,
            },
            // 表单参数
            form: {
                timer:null,
                timeRange:[]
            },
            // 表单校验
            rules: {
                name: [
                    {required: true, message: "请输入名称(可点击自动生成按钮)", trigger: "blur"},
                ],
                timer: [
                    {required: true, message: "请输入考试时长", trigger: "blur"},
                ],
                appoint: [
                    {required: true, message: "请选择是否允许预约考试", trigger: "blur"},
                ],
                fixed: [
                    {required: true, message: "请选择是否固定组卷", trigger: "blur"},
                ],
                timeRange: [
                    {type: 'array', required: true, message: "请选择时间范围", trigger: "blur"}
                ],
                checkeds: [
                    {type: 'array', required: true, message: "请选择范畴", trigger: "blur"}
                ],
                appointDate: [
                    {required: true, message: "请选择考试时间", trigger: "blur"},
                ],
            },
            appoint_form: {},
            exam_record_ids: [],
            //题库列表
            questionList: [],
            questionTotal: null,
            pickerOptions: {
                shortcuts: [{
                    text: '后一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        end.setTime(end.getTime() + 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '后一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        end.setTime(end.getTime() + 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '后三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        end.setTime(end.getTime() + 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            appoint_open: false,//预约抽屉
            allot_open: false,//分配抽屉
            allot_ex: {},
        };
    },
    created() {
        this.getList();
    },
    methods: {
        second_format(row, column) {
            return secondFormat(row.duration);
        },
        /** 查询已经预约的考试id */
        getAppointExamIds() {
            get_appoint_exam_ids().then(response => {
                this.exam_record_ids = response.rows;
            })
        },
        /** 查询考试管理列表 */
        getList() {
            this.loading = true;
            listExam(this.queryParams).then(response => {
                this.examList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
            this.getAppointExamIds();
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.edit_open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                name: null,
                duration: null,
                appoint: null,
                fixed: null,
                startTime: '',
                endTime: '',
                reservedOne: null,
                reservedTwo: null,
                createTime: null,
                sig: 'ratio',
                questionCount: 0,
                timeRange: [],
                checkeds: [],
                checkedTotal: null,
                timer: '',
            };
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 修改按钮操作 */
        handleEdit(row) {
            this.form = {
                id:row.id,
                name:row.name,
                appoint:row.appoint,
                timer:secondFormat(row.duration),
                timeRange:[row.startTime, row.endTime]
            };
            this.edit_open = true;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.resetForm("add_form");
            this.open = true;
            this.getQuestionIdsGroupByTopic();
        },
        /** 提交添加按钮 */
        submitAddForm() {
            this.$refs["add_form"].validate(valid => {
                if (valid) {
                    //自定义校验
                    if (this.form.sig != 'optional') {
                        if (this.form.questionCount == 0) {
                            this.$modal.msgWarning("题目数量不可为0");
                            return;
                        }
                        if (this.form.checkedTotal < this.form.questionCount) {
                            this.$modal.msgWarning("题目数量超过了题库总数");
                            return;
                        }
                        if (this.form.sig == 'average') {//平均选择
                            let length = this.form.checkeds.length;
                            var half = this.form.questionCount % length == 0 ? this.form.questionCount / length : this.form.questionCount / length + 1;
                            for (let i = 0; i < length; i++) {
                                const item = this.form.checkeds[i];
                                if (item.count < half) {
                                    this.$modal.msgWarning("超出题库数量");
                                    return;
                                }
                            }
                        }
                    } else {
                        let allCount = arrSumByKey(this.form.checkeds, 'number');
                        if (allCount === 0) {
                            this.$modal.msgWarning("题目数量不可为0");
                            return;
                        }
                    }
                    this.form.startTime = this.form.timeRange[0];
                    this.form.endTime = this.form.timeRange[1];
                    this.form.duration = timeToSecond(this.form.timer)
                    createExam(this.form).then(response => {
                        this.$modal.msgSuccess("新增成功");
                        this.open = false;
                        this.getList();
                    });
                }
            });
        },
        /** 提交修改按钮 */
        submitEditForm() {
            this.$refs["edit_form"].validate(valid => {
                if (valid) {
                    this.form.startTime = this.form.timeRange[0];
                    this.form.endTime = this.form.timeRange[1];
                    this.form.duration = timeToSecond(this.form.timer)
                    updateExam(this.form).then(response => {
                        this.$modal.msgSuccess("修改成功");
                        this.edit_open = false;
                        this.getList();
                    });
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除考试管理编号为"' + ids + '"的数据项？').then(function () {
                return delExam(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('ex/exam/export', {
                ...this.queryParams
            }, `exam_${nowDateStr()}.xlsx`)
        },
        //--------- 创建测试 ----------------------------
        /** 生成测试名称 */
        generateName() {
            this.form.name = '考试_' + parseTime(new Date, '{y}-{m}-{d}');
        },
        /** 根据范畴分组获取个数 */
        getQuestionIdsGroupByTopic() {
            get_question_ids_group_by_topic().then(response => {
                this.questionList = fillNode(response.data, 'number', 0);
                this.questionTotal = arrSumByKey(response.data, 'count');
                this.loading = false;
            })
        },
        /** 选中题库 */
        handleQuestionChange(selection) {
            this.form.checkeds = selection;
            this.form.checkedTotal = arrSumByKey(selection, 'count');
        },
        //---------- 预约 ----------------------
        contain,
        /** 判断当前时间是否在结束时间之前 */
        beforeNow,
        /** 判断此记录是否可以预约 */
        isCanAppoint(row){
            if (row.appoint != '1' || afterNow(row.endTime)){//如果现在时间在结束时间之后，不可以预约
                return false;
            }
            return true;
        },
        /** 返回时间范围内的所有天 */
        getRange(row) {
            return getRangeDay(row.startTime,row.endTime);
        },
        /** 预约 */
        appoint(row) {
            this.$refs["appoint_form"].validate(valid => {
                if (valid) {
                    appoint({examId: row.id, appointDate: this.appoint_form.appointDate}).then(response => {
                        this.$notify.success('预约成功');
                        this.getList();
                        this.appointCancel(row);
                    })
                }
            });
        },
        appointCancel(row) {//取消预约
            this.appoint_form = {};
            row.visible = false;
        },
        /** 我的预约 */
        handleMyAppoint(row) {
            this.appoint_open = true;
        },
        //----------- 分配 --------------------
        handleAllot(row) {
            this.allot_ex = row;
            this.allot_open = true;
        }
    },
    watch: {
    }
};
</script>
<style>
.customer-table {
    border-style: solid;
    border-color: silver;
    border-width: 1px;
    width: 530px;
    height: 360px;
}

.el-table__row > td {
    border: none;
}

.el-table::before {
    height: 0px;
}
</style>
